function clearRedundantFiles
PATH = '/home/wks';
delete(fullfile(PATH, 'matlab_crash_dump.*'));
delete(fullfile(PATH, 'java.log.*'));

% PATH = '/home/wks/SR-Works/warmStarting';
PATH = '/home/wks/SR-Works/%CascadeFineTuning';
clearAllSolverstateFile(PATH);

function clearAllSolverstateFile(PATH)
if isempty(PATH), return; end

st = dir(fullfile(PATH));
if length(st) == 2, return; end

fprintf('Current Path is %s ...\n', PATH);

ModelPathList = arrayfun(@(x)getSubPathList(PATH, x.name, true), st, 'uniformoutput', false);
cellfun(@clearSolverstateFile, ModelPathList);

SubPathList = arrayfun(@(x)getSubPathList(PATH, x.name, false), st, 'uniformoutput', false);
cellfun(@clearAllSolverstateFile, SubPathList);

function TargetPath = getSubPathList(PATH, folder, bGetModelPath)
TargetPath = '';
if strcmp(folder, '.') || strcmp(folder, '..'), return; end

SubPath = fullfile(PATH, folder);
ModelPath = fullfile(SubPath, 'models');

if bGetModelPath && isdir(ModelPath)
    TargetPath = ModelPath;
    return
end

if ~bGetModelPath && ~isdir(ModelPath) && isdir(SubPath)
    TargetPath = SubPath;
    return
end

function clearSolverstateFile(ModelPath)
if isempty(ModelPath) || ~isdir(ModelPath), return; end

solverstateFiles = dir(fullfile(ModelPath, '*.solverstate'));
if isempty(solverstateFiles), return; end

% only keep the last .solverstate file
k = 1;
[~, idx] = sort({solverstateFiles(:).date});
solverstateFiles = solverstateFiles(idx(1 : end-k));
arrayfun(@(x) delete(fullfile(ModelPath, x.name)), solverstateFiles);
